import Vue from 'vue'
import VueRouter from 'vue-router'
import { message } from 'element-ui'

import Login from '../components/Login'
import Home from '../components/Home'
import Welcome from '../components/Welcome'
import Users from '../components/user/Users'
import Roles from '../components/power/Roles'
import Rights from '../components/power/Rights'
import Goods from '../components/commodity/Goods'
import Params from '../components/commodity/Params'
import Categories from '../components/commodity/Categories'
import Orders from '../components/order/Orders'
import Reports from '../components/data/Reports'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: Login
  },
  {
    path: '/',
    component: Home,
    children: [
      {
        path: '/home',
        component: Welcome
      },
      // 用户列表
      {
        path: '/users',
        component: Users
      },
      // 角色列表
      {
        path: '/roles',
        component: Roles
      },
      // 权限列表
      {
        path: '/rights',
        component: Rights
      },
      // 商品列表
      {
        path: '/goods',
        component: Goods
      },
      // 分类参数
      {
        path: '/params',
        component: Params
      },
      // 商品分类
      {
        path: '/categories',
        component: Categories
      },
      // 订单列表
      {
        path: '/orders',
        component: Orders
      },
      // 数据列表
      {
        path: '/reports',
        component: Reports
      }
    ]
  }
  // { path: '*', redirect: '/home' }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  const tokenStr = window.sessionStorage.getItem('token')
  // to 将要访问的路径
  // from 代表从哪个路径跳转而来
  // next 是一个函数，表示放行
  if (to.path !== '/login') {
    if (!tokenStr) {
      message.error('请登录!')
      return next('/login')
    }
    return next()
  }
  next()
})

export default router
